`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date:    18:36:31 10/28/2014 
// Design Name: 
// Module Name:    Tx 
// Project Name: 
// Target Devices: 
// Tool versions: 
// Description: 
//
// Dependencies: 
//
// Revision: 
// Revision 0.01 - File Created
// Additional Comments: 
//
//////////////////////////////////////////////////////////////////////////////////
module Tx( input [7:0] d_in, input tx_start, input tick, output reg tx, output reg tx_done
    );
	 
//Declaracion de estados
localparam [3:0]  IDLE = 4'b0001,
						START = 4'b0010,
						DATA = 4'b0100,
						STOP = 4'b1000;

//Declaración de señales (las utilizare para el elemento de memoria por lo tanto son tipo REGISTRO)
reg[3:0] current_state, next_state;
integer tick_counter; //contador de ticks
integer n;		//Posicion dentro del arreglo interno de datos


//Registro de estado (Memoria)
always @(posedge tick) begin
	current_state = next_state;
end
		
//Logica de cambio de estado						
always @*
begin

		case(current_state)

			IDLE:
				begin
					tx = 1;
					tx_done = 0;
					//buffer = 0;
					if(tx_start == 1) begin //Bit de start
						next_state = START;
						tick_counter = 0;
					end
				end

			START:
				begin
					tx = 0;	//Bit de start de la trama
					tx_done = 0;
					
					if(tick == 1) begin
						if(tick_counter == 15) begin
							next_state = DATA;
							tick_counter = 0;
							n = 0;					//Posicion dentro del bffer de salida
						end
						else tick_counter = tick_counter + 1;
					end
				end
				
			DATA:
				begin	
					tx = d_in[n];
					tx_done = 0;
					if(tick == 1) begin
						if(tick_counter == 15) begin						
							n = n + 1;
							if(n == 8) begin
								next_state = STOP;
								n = 0;
							end
							tick_counter = 0;
						end	
						else tick_counter = tick_counter + 1;
					end
				end
			
			STOP:
				begin
					tx = 1; //bit de end
					tx_done = 1;
					if(tick == 1) begin
						if(tick_counter == 15) begin						
							next_state = IDLE;
							tick_counter = 0;
						end
						else tick_counter = tick_counter + 1;
					end
				end
				
			default:
				begin
					tx_done = 0;
					tx = 1;
					next_state = IDLE;
					
				end
				
		endcase
	
end


endmodule
